package edu.cmu.cs.webapp.ioms.ui.dialogs.order;

import java.text.NumberFormat;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import edu.cmu.cs.webapp.ioms.models.IOMSFactory;
import edu.cmu.cs.webapp.ioms.models.LineItem;
import edu.cmu.cs.webapp.ioms.models.Product;
import edu.cmu.cs.webapp.ioms.ui.dialogs.product.BrowseProductsDialog;
import edu.cmu.cs.webapp.ioms.utils.SWTUtils;

/**
 * 
 * @author Christian
 * 
 */
public class OrderItemDialog extends TitleAreaDialog {

	private Text _product;
	private Text _quantity;
	private Combo _packageSize;
	private Button _browseBtn;

	private LineItem _model;
	private Product _prodModel;
	private Text _remark;

	/**
	 * @param parentShell
	 */
	public OrderItemDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * @param parentShell
	 * @param isUpdate
	 */
	public OrderItemDialog(Shell parentShell, LineItem model) {
		this(parentShell);
		this._model = model;
	}

	protected Control createDialogArea(Composite parent) {
		Composite container = SWTUtils.createComposite(parent, 3, SWT.DEFAULT,
				1);

		if (this._model != null) {
			setTitle("Update Order Line Item");
		} else {
			setTitle("Add Order Line Item");
		}

		setMessage("Services deliverable to customers");

		/* Product */
		Label label = new Label(container, SWT.NULL);
		label.setText("Product:"); //$NON-NLS-1$

		_product = new Text(container, SWT.BORDER | SWT.SINGLE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 1;
		_product.setLayoutData(gd);

		_browseBtn = new Button(container, SWT.FLAT);
		_browseBtn.setText("Browse...");
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 1;
		gd.grabExcessHorizontalSpace = false;
		_browseBtn.setLayoutData(gd);
		_browseBtn.addSelectionListener(new SelectionListener() {

			public void widgetDefaultSelected(SelectionEvent e) {
			}

			public void widgetSelected(SelectionEvent e) {
				BrowseProductsDialog dlg = new BrowseProductsDialog(getShell());
				if (dlg.open() == IDialogConstants.OK_ID) {
					_prodModel = dlg.getSelectedModel();
					_product.setText(_prodModel.getProd_name() + "(#"
							+ _prodModel.getProd_id() + ")");
				}
				validateInput();
			}
		});

		/* Quantity */
		label = new Label(container, SWT.NULL);
		label.setText("Quantity:"); //$NON-NLS-1$

		_quantity = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		_quantity.setLayoutData(gd);
		_quantity.addModifyListener(new ModifyListener() {
			
			@Override
			public void modifyText(ModifyEvent event) {
				validateInput();
			}
		});

		/* Package Size */
		label = new Label(container, SWT.NULL);
		label.setText("Package Size:"); //$NON-NLS-1$

		_packageSize = new Combo(container, SWT.BORDER | SWT.READ_ONLY);
		_packageSize.setItems(new String[] { "Small", "Medium", "Large" });
		_packageSize.select(0);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		_packageSize.setLayoutData(gd);

		/* Remark */
		label = new Label(container, SWT.NULL);
		label.setText("Remark:"); //$NON-NLS-1$

		_remark = new Text(container, SWT.BORDER | SWT.SINGLE);
		gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		_remark.setLayoutData(gd);

		if (this._model != null) {
			loadFromExistingModel();
		}

		validateInput();
		
		return container;
	}

	private void loadFromExistingModel() {
		if (_model == null) {
			return;
		} else {
			this._prodModel = _model.getProduct();
			this._packageSize.setText(_model.getUnit());
			this._product.setText(_prodModel.getProd_name() + "(#"
					+ _prodModel.getProd_id() + ")");
			this._quantity.setText(NumberFormat.getInstance().format(
					_model.getQuantity()));
			this._remark.setText(_model.getRemark());
		}
	}

	@Override
	protected void okPressed() {
		if (this._model == null) {
			this._model = IOMSFactory.eINSTANCE.createLineItem();
		}

		// this._model.setItem_id(Integer.valuthis._id.getText());
		// this._model.setProduct(value)
		this._model.setProduct(this._prodModel);
		this._model.setQuantity(Integer.parseInt(this._quantity.getText()));
		this._model.setRemark(this._remark.getText());
		this._model.setUnit(this._packageSize.getItem(this._packageSize
				.getSelectionIndex()));

		super.okPressed();
	}

	public LineItem getModel() {
		return this._model;
	}

	public void setModel(LineItem model) {
		this._model = model;
	}

	private void validateInput() {
		boolean valid = true;
		String errorMessage = null;
		if (valid && (this._prodModel == null)) {
			valid = false;
			errorMessage = "Choose one product to associate with this order item";
		}

		if (valid
				&& (this._quantity.getText() == null || this._quantity
						.getText().length() == 0)) {
			valid = false;
			errorMessage = "Item quantity must be specified";
		}

		if (valid) {
			try {
				Double.valueOf(this._quantity.getText().trim());
			} catch (NumberFormatException e) {
				valid = false;
				errorMessage = "Invalid input... quantity value must be a number";
			}
		}

		if (!valid && errorMessage != null) {
			setErrorMessage(errorMessage);
			enableOKButton(false);
		} else {
			setErrorMessage(null);
			enableOKButton(true);
		}
	}

	private void enableOKButton(boolean enable) {
		Button okBtn = getButton(IDialogConstants.OK_ID);
		if (okBtn != null) {
			okBtn.setEnabled(enable);
		}
	}
}
